import React, { useEffect, useState } from 'react'
import { Card, Button, Skeleton, Toast, Dialog } from 'antd-mobile'
import { useLocation, useNavigate } from 'react-router-dom'
import TopNavbar from '../../components/TopNavbar'
import styles from './index.module.css'
import { searchDoctors, fetchSlots, submitBooking, pushRecentDoctor } from '../../services/registerService'

const DoctorList = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const deptId = location.state?.deptId
  const areaId = location.state?.areaId
  const deptName = location.state?.deptName
  const [loading, setLoading] = useState(true)
  const [doctors, setDoctors] = useState([])

  useEffect(() => {
    setLoading(true)
    searchDoctors({ deptId, areaId }).then(res => setDoctors(res)).finally(() => setLoading(false))
  }, [deptId, areaId])

  const handleBook = async (doctor) => {
    try {
      const slots = await fetchSlots(doctor.id)
      if (!slots.length) {
        Toast.show({ content: '该医生今日无号源', position: 'center' })
        return
      }
      const pick = slots[0]
      const ok = await Dialog.confirm({ content: `确认预约 ${doctor.name}（${doctor.title}）\n时间：${pick.time}\n费用：¥${doctor.fee}` })
      if (!ok) return
      const result = await submitBooking({ doctorId: doctor.id, slotId: pick.id })
      pushRecentDoctor({ id: doctor.id, name: doctor.name, title: doctor.title })
      navigate('/register/result', { state: { success: result.success, bookingId: result.bookingId, payAmount: result.payAmount, doctor, slot: pick } })
    } catch (err) {
      const msg = err?.message || '预约失败，请稍后重试'
      Toast.show({ content: msg, position: 'center' })
    }
  }

  return (
    <div className={styles.page}>
      <TopNavbar title={deptName ? `${deptName}·医生列表` : '医生列表'} showBack onBack={() => navigate(-1)} />
      <div className={styles.container}>
        {loading ? (
          <div className={styles.doctorList}>
            {Array.from({ length: 3 }).map((_, i) => (
              <Card key={i} className={styles.doctorCard}>
                <Skeleton.Title animated />
                <Skeleton.Paragraph animated lineCount={2} />
              </Card>
            ))}
          </div>
        ) : (
          <div className={styles.doctorList}>
            {doctors.length === 0 ? (
              <div className={styles.empty}>暂无相关医生</div>
            ) : doctors.map(d => (
              <Card key={d.id} className={styles.doctorCard}>
                <div className={styles.docHeader}>
                  <div className={styles.avatar}>{d.avatar}</div>
                  <div className={styles.docMeta}>
                    <div className={styles.docName}>{d.name} · {d.title}</div>
                    <div className={styles.docDept}>{d.deptName}</div>
                    <div className={styles.docSchedule}>{d.schedule}</div>
                  </div>
                  <div className={styles.docFee}>¥{d.fee}</div>
                </div>
                <div className={styles.docFooter}>
                  <div className={styles.badges}>
                    <div className={styles.remain}>{d.remain > 0 ? `剩余号源 ${d.remain}` : '号源已满'}</div>
                    {d.supportIM && <div className={styles.tag}>支持问诊</div>}
                  </div>
                  <Button color='primary' size='small' disabled={d.remain <= 0} onClick={() => handleBook(d)}>立即挂号</Button>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default DoctorList


